import time
from tinydb import TinyDB, where
import pyecharts.options as opts
from pyecharts.charts import Line
#直接从ping值出图
#python3 -m uvicorn fastapi0:app --host '0.0.0.0' --reload
from fastapi import FastAPI
from starlette.requests import Request
import os
from fastapi.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles
from starlette.responses import RedirectResponse
from typing import List
from fastapi import FastAPI, File, UploadFile
from starlette.responses import HTMLResponse
import json
from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.globals import ThemeType
from pyecharts.commons.utils import JsCode
from pyecharts.charts import Scatter
from pyecharts.charts import Line
from shutil import copyfile
import datetime
from ping3 import ping
import requests
import json
from pyecharts.charts import Bar, Grid, Line, Liquid, Page, Pie
from pyecharts.globals import CurrentConfig
from numpy import *
from pyecharts.commons.utils import JsCode

color_function = """
        function (params) {
            if (params.value >= 0) {
                return 'red';
            
            }
            return 'green';
        }
        """

#from pyecharts import Page


def dianzi1(q):
    #response = requests.get('http://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get?lmt=0&klt=101&secid=90.BK0473&fields1=f1,f2,f3,f7&fields2=f51,f52', timeout=2)
    #深圳 response = requests.get('http://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get?lmt=0&klt=101&secid=0.399001&fields1=f1,f2,f3,f7&fields2=f51,f52,f54', timeout=2)
    response = requests.get('http://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get?lmt=0&klt=101&secid={}&fields1=f1,f2,f3,f7&fields2=f51,f52,f54'.format(q), timeout=2)
    text=response.text
    #http://push2.eastmoney.com/api/qt/ulist.np/get?fltt=2&secids=90.BK0471&fields=f62
    response1 = requests.get('http://push2.eastmoney.com/api/qt/ulist.np/get?fltt=2&secids={}&fields=f62'.format(q), timeout=2)
    text1=response1.text
    #print(text,type(text))
    json0=json.loads(text)
    json1=json.loads(text1)
    x=json0['data']['klines']
    x1=json1['data']['diff'][0]['f62']/100000000
    print("x1:",x1)
    
    dates=list(map(lambda x:x.split(',')[0][5:],x))
    dates.append('当前')
    values=list(map(lambda x:float(x.split(',')[1])/100000000,x))
    values.append(x1)
    print("len：",len(dates))
    #values=list(map(lambda x:int(float(x.split(',')[1])+float(x.split(',')[2])),x))
    return dates,values

def get_value(id):
    headers = {'Referer':'http://fundf10.eastmoney.com/jjjz_%s.html'%(id)}
    response = requests.get('http://api.fund.eastmoney.com/f10/lsjz?callback=jQuery18305940568224296903_1595409948652&fundCode=%s&pageIndex=1&pageSize=102'%(id),headers=headers)
    text=response.text[41:-1]
    #print(text)
        #http://push2.eastmoney.com/api/qt/ulist.np/get?fltt=2&secids=90.BK0471&fields=f62
    #response1 = requests.get('http://push2.eastmoney.com/api/qt/ulist.np/get?fltt=2&secids={}&fields=f62'.format(q), timeout=2)
    #text1=response1.text
    json0=json.loads(text)
    #print(json0['Data']['LSJZList'])
    X=[]
    Y=[]
    for item in json0['Data']['LSJZList'][::-1]:
        X.append(item['FSRQ'][5:])
        Y.append(item['LJJZ'])
    print(X,Y)
    return X, Y

app = FastAPI()
location='../static'
app.mount('/static', StaticFiles(directory=location), name='static') 
CurrentConfig.ONLINE_HOST = "/static/"

dict_ip={}
@app.get("/")
def root():
    return RedirectResponse(url='/charts')








def charts1(q,title):
    print(q)
    X,Y=dianzi1(q)
    print(X)
    print(Y)
    #total=0

    #a=[1,2,3,4]
    #Y1=list(map(lambda x:sum0(x),Y))
    line=Line(init_opts=opts.InitOpts(js_host='/static/',width="1600px",height="400px",animation_opts=opts.AnimationOpts(animation_duration=500)))

    line.add_xaxis(X)

    #x=['1','2','3','4','5','6']
    #y=[1,2,3,4,5,6]
    #y1=[0,1,2,3,4,5]
    #c = (
        #Bar(init_opts=opts.InitOpts(js_host='./static',theme=ThemeType.LIGHT,width="2000px",animation_opts=opts.AnimationOpts(animation_duration=3000)))
    #line=Line(init_opts=opts.InitOpts(js_host='/static/',theme=ThemeType.LIGHT,width=width,animation_opts=opts.AnimationOpts(animation_duration=500)))
        #Bar()
    #line.add_xaxis(x)

    line.add_yaxis(title, Y,label_opts=opts.LabelOpts(is_show=False),   markpoint_opts=opts.MarkPointOpts(
        data=[
         #   opts.MarkPointItem(type_="max", name="最大值"),
         #   opts.MarkPointItem(type_="min", name="最小值"),
        ]
    ),             markline_opts=opts.MarkLineOpts(
        #data=[opts.MarkLineItem(type_="average", name="平均值")]
    ),)
    #line.add_yaxis('hello1', y1)
        #.add_yaxis("商家B", [15, 25, 16, 55, 48, 8])
    #line.set_global_opts(xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=12,interval=0,rotate=-45)),title_opts=opts.TitleOpts(title=item_id),toolbox_opts=opts.ToolboxOpts())
    line.set_global_opts(xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=9,interval=0,rotate=-90)),title_opts=opts.TitleOpts(title=""))

    return line


def charts2(q,title):
    print(q)
    X,Y=dianzi1(q)
    print(X)
    print(Y)
    b = mean(Y)
    Y1=list(map(lambda x:x-b,Y))
    #total=0

    #a=[1,2,3,4]
    #Y1=list(map(lambda x:sum0(x),Y))
    line=Bar(init_opts=opts.InitOpts(js_host='/static/',width="1600px",height="400px",animation_opts=opts.AnimationOpts(animation_duration=500)))

    line.add_xaxis(X)

    #x=['1','2','3','4','5','6']
    #y=[1,2,3,4,5,6]
    #y1=[0,1,2,3,4,5]
    #c = (
        #Bar(init_opts=opts.InitOpts(js_host='./static',theme=ThemeType.LIGHT,width="2000px",animation_opts=opts.AnimationOpts(animation_duration=3000)))
    #line=Line(init_opts=opts.InitOpts(js_host='/static/',theme=ThemeType.LIGHT,width=width,animation_opts=opts.AnimationOpts(animation_duration=500)))
        #Bar()
    #line.add_xaxis(x)

    line.add_yaxis(title, Y1, color=JsCode(color_function), label_opts=opts.LabelOpts(is_show=False),   markpoint_opts=opts.MarkPointOpts(
        data=[
           # opts.MarkPointItem(type_="max", name="最大值"),
           # opts.MarkPointItem(type_="min", name="最小值"),
        ]
    ),             markline_opts=opts.MarkLineOpts(
        #data=[opts.MarkLineItem(type_="average", name="平均值")]
    ),)
    #line.add_yaxis('hello1', y1)
        #.add_yaxis("商家B", [15, 25, 16, 55, 48, 8])
    #line.set_global_opts(xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=12,interval=0,rotate=-45)),title_opts=opts.TitleOpts(title=item_id),toolbox_opts=opts.ToolboxOpts())
    line.set_global_opts(xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=9,interval=0,rotate=-90)),title_opts=opts.TitleOpts(title=""))

    return line

#基金历史净值
def charts_value(q,title,min0,max0):
    print(q)
    X,Y=get_value(q)
    print(X)
    print(Y)
    #total=0

    #a=[1,2,3,4]
    #Y1=list(map(lambda x:sum0(x),Y))
    line=Line(init_opts=opts.InitOpts(js_host='/static/',width="1600px",height="400px",animation_opts=opts.AnimationOpts(animation_duration=500)))

    line.add_xaxis(X)

    #x=['1','2','3','4','5','6']
    #y=[1,2,3,4,5,6]
    #y1=[0,1,2,3,4,5]
    #c = (
        #Bar(init_opts=opts.InitOpts(js_host='./static',theme=ThemeType.LIGHT,width="2000px",animation_opts=opts.AnimationOpts(animation_duration=3000)))
    #line=Line(init_opts=opts.InitOpts(js_host='/static/',theme=ThemeType.LIGHT,width=width,animation_opts=opts.AnimationOpts(animation_duration=500)))
        #Bar()
    #line.add_xaxis(x)

    line.add_yaxis(title, Y, color='blue',label_opts=opts.LabelOpts(is_show=False),   markpoint_opts=opts.MarkPointOpts(
        data=[
            #opts.MarkPointItem(type_="max", name="最大值"),
            #opts.MarkPointItem(type_="min", name="最小值"),
        ]
    ),             markline_opts=opts.MarkLineOpts(
        #data=[opts.MarkLineItem(type_="average", name="平均值")]
    ),)
    line.set_global_opts(yaxis_opts=opts.AxisOpts(
            name="净值(元)",
            type_="value",
            min_=min0,
            max_=max0,))
    #line.add_yaxis('hello1', y1)
        #.add_yaxis("商家B", [15, 25, 16, 55, 48, 8])
    #line.set_global_opts(xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=12,interval=0,rotate=-45)),title_opts=opts.TitleOpts(title=item_id),toolbox_opts=opts.ToolboxOpts())
    line.set_global_opts(xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=9,interval=0,rotate=-90)),title_opts=opts.TitleOpts(title=""))

    return line    


@app.get("/charts")
def charts0():
    line00=charts1('1.000001','上海 主力增量 (亿)')
    line01=charts2('1.000001','上海 主力增量均值修正 (亿)')
    line02=charts_value('005919','中证500 005919 历史净值',0.8,1.3)
    line10=charts1('0.399001','深圳 主力增量 (亿)')
    line11=charts2('0.399001','深圳 主力增量均值修正 (亿)')
    line12=charts_value('009472','深圳009472 历史净值',1.2,1.8)
    line20=charts1('0.399006','创业板 主力增量 (亿)')
    line21=charts2('0.399006','创业板 主力增量均值修正 (亿)')
    line22=charts_value('001593','创业板001593 历史净值',0.7,1.2)
    line30=charts1('90.BK0447','电子信息 主力增量 (亿)')
    line31=charts2('90.BK0447','电子信息 主力增量均值修正 (亿)')
    line32=charts_value('001618','电子001618 历史净值',1,1.7)
    line40=charts1('90.BK0473','券商 主力增量 (亿)')
    line41=charts2('90.BK0473','券商 主力增量均值 (亿)')
    line42=charts_value('008591','券商008591 历史净值',0.9,1.5)
    line50=charts1('90.BK0737','计算机软件 主力增量 (亿)')
    line51=charts2('90.BK0737','计算机软件 主力均值修正增量柱状图 (亿)')
    line52=charts_value('001630','计算机软件001630 历史净值',0.7,1.2)
    line60=charts1('90.BK0459','元件半导体 主力增量 (亿)')
    line61=charts2('90.BK0459','元件半导体 主力增量均值修正 (亿)')
    line62=charts_value('007301','半导体芯片007301 历史净值',1.4,2.8)
    line70=charts1('90.BK0727','医疗 主力增量 (亿)')
    line71=charts2('90.BK0727','医疗 主力增量均值修正 (亿)')
    line72=charts_value('001551','医药001551 历史净值',0.7,1.4)
    line80=charts1('90.BK0480','航天军工 主力增量 (亿)')
    line81=charts2('90.BK0480','航天军工 主力增量均值修正 (亿)')
    line82=charts_value('005693','军工005693 历史净值',0.7,1.2)
    line90=charts1('90.BK0438','食品饮料 主力增量 (亿)')
    line91=charts2('90.BK0438','食品饮料 主力增量均值修正 (亿)')
    line92=charts_value('001632','食品饮料001632 历史净值',1.5,3)
    #line100=charts1('90.BK0474','保险 主力增量 亿')
    line110=charts1('90.BK0475','银行 主力增量 (亿)')
    line111=charts2('90.BK0475','银行 主力增量均值修正 (亿)')
    line112=charts_value('001595','银行001595 历史净值',1,1.5)
    #line12=charts('90.BK0728','环保 主力增量 亿')
    #BK0737
    #BK0473
    
    page = Page()
    page.add(
        line00,
        line01,
        line02,
        line10,
        line11,
        line12,
        line20,
        line21,
        line22,
        line30,
        line31,
        line32,
        line40,
        line41,
        line42,
        line50,
        line51,
        line52,
        line60,
        line61,
        line62,
        line70,
        line71,
        line72,
        line80,
        line81,
        line82,
        line90,
        line91,
        line92,
        #line100,
        line110,
        line111,
        line112,
        #line12,
        #line,
    #    line.render_embed(),

    )
    y=page.render_embed()
    #page.render("page_draggable_layout.html")


    return HTMLResponse(content=y)